<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.id?$t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" :width="lang === 'zh'?'610px':'720px'" top='5vh' @close='close'>
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :model="record" :label-width="lang === 'zh'?'100px':'160px'" :rules="rules" label-position="left" style="margin:0 20px;">
        <el-form-item :label="$t('带宽规则名称')" prop="name">
          <el-input v-emoji v-model="record.name" ref="recordName" style="width:217px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('所属接口')" prop="inter" v-if="!record.id">
          <el-select v-model="record.inter" ref="inter" filterable size='small' @change="classArrayChange">
            <el-option v-for="(item,index) in policyList" :id="`bandwidth-inter${index}`" :key="item.name" :label="item.name" :value="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('所属带宽分类')" prop="class_name">
          <el-select v-model="record.class_name" ref="className" filterable :disabled='record.id !== null' size='small'>
            <el-option v-for="(item,index) in classList" :id="`bandwidth-class_name${index}`" :key="item.name" :label="item.name" :value="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('IP类型')" prop="ip_type">
          <el-radio v-model="record.ip_type" class="ipv4" label="ipv4" :disabled='record.id !== null'>IPv4</el-radio>
          <el-radio v-model="record.ip_type" class="ipv6" label="ipv6" :disabled='record.id !== null'>IPv6</el-radio>
        </el-form-item>
        <el-form-item :label="$t('源IP')" prop="src">
          <el-select v-model="record.src" ref="src" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in filMac(sipList)" :id="`bandwidth-src${index}`" :key="item.id" :label="item.nameShow" :value="item.name">
            </el-option>
          </el-select>
          <addr-dialog @commandList='commandList' :nameType='"src"'></addr-dialog>
        </el-form-item>
        <el-form-item :label="$t('目的IP')" prop="dst">
          <el-select v-model="record.dst" ref="dst" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in filMac(dipList)" :id="`bandwidth-dst${index}`" :key="item.id" :label="item.nameShow" :value="item.name">
            </el-option>
          </el-select>
          <addr-dialog @commandList='commandList' :nameType='"dst"'></addr-dialog>
        </el-form-item>
        <el-form-item :label="$t('应用')" prop="app">
          <el-select v-model="record.app" ref="app" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in appList" :id="`bandwidth-app${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <AppDialog @appDataList='appDataList'></AppDialog>
        </el-form-item>
        <el-form-item :label="$t('服务')" prop="service">
          <el-select v-model="record.service" ref="service" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in iservicepsList" :id="`bandwidth-service${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <ServerDialog @serviceList='serviceList'></ServerDialog>
        </el-form-item>
        <el-form-item :label="$t('用户')" prop="user">
          <el-select v-model="record.user" ref="user" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in userList" :id="`bandwidth-user${index}`" :key="item.name" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <el-button type="primary" plain size='small' style="margin-left:10px" @click="userDialogVisible" class="userDialogVisible">{{$t('新建用户')}}</el-button>
          <el-button type="primary" plain size='small' @click="groupDialogVisible" class="groupDialogVisible">{{$t('新建用户组')}}</el-button>
          <group-dialog v-if="groupDialog" ref="refGroupDialogVisible" @userListData='userListData'></group-dialog>
          <user-dialog v-if="userDialog" ref="refUserDialogVisible" @userListData='userListData'></user-dialog>
        </el-form-item>
        <el-form-item :label="$t('时间')" prop="time">
          <el-select v-model="record.time" ref="time" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in timeList" :id="`bandwidth-time${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <TimeDialog @timeDataList='timeDataList'></TimeDialog>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getBandWidthArray, addRule, editRule } from '@/api/network/bandwidth'
import { getAddrGroupArray } from '@/api/list/addr-group'
import { getAddrArray } from '@/api/list/addr'
import { getServiceArray, getServiceReArray } from '@/api/list/server'
import { getTimeArray } from '@/api/list/time'
import { getAppArray, getAppReArray } from '@/api/list/app'
import { getGroupUserInfo, getUserArray } from '@/api/user/user'
import addrDialog from './AddrDialog'
import ServerDialog from './ServerDialog'
import TimeDialog from './TimeDialog'
import AppDialog from './AppDialog'
import GroupDialog from './userTools/GroupDialog'
import UserDialog from './userTools/UserDialog'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'BandwidthDialog',
  components: {
    addrDialog,
    ServerDialog,
    TimeDialog,
    AppDialog,
    GroupDialog,
    UserDialog
  },
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    return {
      lang: this.$i18n.locale,
      dialogVisible: false,
      userDialog: false,
      groupDialog: false,
      record: {
        id: null,
        name: '',
        inter: '',
        class_name: '',
        ip_type: 'ipv4',
        src: '',
        dst: '',
        service: '',
        app: '',
        user: '',
        time: ''
      },
      recordCopy: {
        id: null,
        name: '',
        inter: '',
        class_name: '',
        ip_type: 'ipv4',
        src: '',
        dst: '',
        service: '',
        app: '',
        user: '',
        time: ''
      },
      sipList: [],
      dipList: [],
      userList: [],
      iservicepsList: [],
      appList: [],
      timeList: [],
      policyList: [], // 接口列表
      classList: [],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        inter: [{ required: false, validator: validateName, trigger: 'blur' }],
        class_name: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  methods: {
    filMac(list=[]) { 
      return list.filter(item => item.ip_type !== 7) 
    },
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['recordName']
        const selectData = ['className', 'src', 'dst', 'app', 'service', 'user', 'time']
        inputClass(this.$refs, data)
        selectClass(this.$refs, selectData)
        if (!this.record.id) {
          selectClass(this.$refs, ['inter'])
        }
      })
      if (data) {
        Object.keys(this.record).forEach((key) => {
          this.record[key] = data[key] || ''
        })
        this.record.old_name = data.name
      } else {
        getBandWidthArray().then(res => {
          if (res.status === 0) {
            this.policyList = res.info
            if (!data && this.policyList && this.policyList.length > 0) {
              this.record.inter = this.policyList[0].name
              this.classArrayChange(this.record.inter)
            }
          }
        })
      }
      this.commandList()
      this.serviceList()
      this.timeDataList()
      this.appDataList()
      this.userListData()
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.record.id) {
            addRule(this.record).then(res => {
              if (res.status === 0) {
                this.$message({
                  message: this.$t('添加成功'),
                  type: 'success'
                })
                this.close()
                this.$parent.listData()
              }
            })
          } else {
            editRule(this.record).then(res => {
              if (res.status === 0) {
                this.$message({
                  message: this.$t('编辑成功'),
                  type: 'success'
                })
                this.close()
                this.$parent.listData()
              }
            })
          }
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.sipList = []
      this.dipList = []
      this.userList = []
      this.iservicepsList = []
      this.appList = []
      this.timeList = []
      this.policyList = []
      this.classList = []
      this.$refs.form.resetFields()
    },
    userDialogVisible () {
      this.userDialog = true
      this.$nextTick(() => {
        this.$refs.refUserDialogVisible.init()
      })
    },
    groupDialogVisible () {
      this.groupDialog = true
      this.$nextTick(() => {
        this.$refs.refGroupDialogVisible.init()
      })
    },
    commandList (data, nameType, name) {
      this.sipList = []
      this.dipList = []
      getAddrArray().then(response => {
        if (response.status === 0) {
          getAddrGroupArray().then(res => {
            if (res.status === 0) {
              // this.sipList = response.info.concat(res.info)
              // this.dipList = response.info.concat(res.info)
              for (let item of response.info) {
                item.nameShow = this.$t('地址-') + item.name
                this.sipList.push(item)
                this.dipList.push(item)
              }
              for (let item of res.info) {
                item.nameShow = this.$t('地址组-') + item.name
                this.sipList.push(item)
                this.dipList.push(item)
              }
            }
          })
        }
      })
      if (data && nameType === 'src') {
        this.record.src = name
      } else if (data && nameType === 'dst') {
        this.record.dst = name
      }
    },
    serviceList (data) {
      this.iservicepsList = []
      getServiceArray().then(response => {
        if (response.status === 0) {
          getServiceReArray().then(res => {
            if (res.status === 0) {
              this.iservicepsList = response.info.concat(res.info)
            }
          })
        }
      })
      if (data) {
        this.record.service = data.name
      }
    },
    timeDataList (data) {
      this.timeList = []
      getTimeArray().then(response => {
        if (response.status === 0) {
          this.timeList = response.info
        }
      })
      if (data) {
        this.record.time = data.name
      }
    },
    appDataList (data, appType) {
      this.appList = []
      getAppArray().then(response => {
        if (response.status === 0) {
          getAppReArray().then(res => {
            if (res.status === 0) {
              this.appList = response.info.concat(res.info)
            }
          })
        }
      })
      if (data) {
        this.record.app = data.name
      }
    },
    userListData (name) {
      getGroupUserInfo({ name: 'root' }).then(res => {
        if (res.status === 0) {
          getUserArray().then(response => {
            if (response.status === 0) {
              var groupList = response.info
              groupList.splice(0, 1)
              this.userList = res.info.concat(groupList)
              if (name) {
                this.record.user = name
              }
            }
          })
        }
      })
    },
    classArrayChange (name) {
      this.classList = []
      this.record.class_name = ''
      for (var item of this.policyList) {
        if (item.name === name) {
          // for (const index in item.child) {
          //   if (!item.child[index].child || item.child[index].child.length === 0 || (item.child[index].child.length > 0 && item.child[index].child[0].class_name)) {
          //     this.classList.push(item.child[index])
          //   } else if (!item.child[index].child || item.child[index].child.length === 0 || (item.child[index].child.length > 0 && item.child[index].child[0].parent_name)) {
          //     item.child[index].child.forEach(rule => {
          //       this.classList.push(rule)
          //     })
          //   }
          // }
          for (let item2 of item.child) {
            if (!item2.child || item2.child.length === 0 || (item2.child.length > 0 && item2.child[0].class_name)) {
              this.classList.push(item2)
            }
          }
          break
        }
      }
      if (this.classList.length > 0) {
        this.record.class_name = this.classList[0].name
      }
    }
  }
}
</script>
<style lang="less" scoped>
.flowDialogSwitch {
  .el-switch {
    margin-left: 15px;

    /deep/ .el-switch__core {
      &::before {
        content: "禁用";
        color: #fff;
        position: absolute;
        // font-size: 14px;
        transform: scale(0.85);
        left: 22px;
      }
    }

    &.switch-is-actived {
      /deep/ .el-switch__core {
        &::before {
          content: "启用";
          left: 8px;
          transform: scale(0.85);
        }
      }
    }
  }
}
</style>
